#include <string.h>
#include <stdlib.h>
#include <iostream>

using std::cout;
using std::endl;

void *operator new(size_t sz)
{
    cout << "void *operator new(size_t )" << endl;
    //函数体该怎么实现呢
    void *pret = malloc(sz);

    return pret;
}

void operator delete(void *ptr)
{
    cout << "void operator delete(void *)" << endl;
    free(ptr);
}

class Student
{
public:
    Student(const char *name, int id)
    : _name(new char[strlen(name) + 1]())
    , _id(id)
    {
        cout << "Student(const char *, int)" <<endl;
        strcpy(_name, name);
    }
#if 0
    //申请原始的未初始化的空间
    static void *operator new(size_t sz)
    {
        cout << "void *operator new(size_t )" << endl;
        //函数体该怎么实现呢
        void *pret = malloc(sz);

        return pret;
    }

    static void operator delete(void *ptr)
    {
        cout << "void operator delete(void *)" << endl;
        free(ptr);
    }
#endif

    void print() const
    {
        if(_name)
        {
            cout << "name: " << _name << endl; 
        }
        cout << "id: " << _id << endl;
    }

    //dt)  = del to )
    ~Student()
    {
        cout << "~Student()" << endl;
        if(_name)
        {
            delete [] _name;
            _name = nullptr;
        }
    }

private:
    char *_name;
    int _id;
};

void test()
{
    /* Student stu("xiaohong", 4201);//栈对象 */
    /* stu.print(); */

    Student *pstu = new Student("lili", 4321);
    pstu->print();

    //Q：对象的销毁与析构函数的执行是不是等价的?
    //A:不等价，对于堆对象而言，析构函数的执行只是对象销毁
    //中的其中一个步骤,除此之外，对象销毁还会将对象本身占用
    //的内存回收掉
    //对于栈对象而言，对象的销毁与析构函数的执行是等价的
    delete pstu;
    pstu = nullptr;
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

